package equappcontrollers

import (
	"github.com/astaxie/beego"
	"fmt"
	"github.com/astaxie/beego/orm"
	"smartcap-api/models"
	"github.com/garyburd/redigo/redis"
	"time"
)

//告警相关的处理
type AlarmController struct {
	beego.Controller
}

//设备SOS告警信息接口,将告警信息发布到redis，并记录告警信息
func (c *AlarmController) Upwardwarning() {
	//fmt.Println("获取到设备的紧急告警信息")
	FileLogs.Info("获取到设备的紧急告警信息")
	deviceid := c.GetString("deviceid")
	o := orm.NewOrm()
	timeUnix:=time.Now().Unix()
	timeStr:=time.Now().Format("2006-01-02 15:04:05")

	//查询该设备所属公司
	var labelrows []models.LabelInfo
	if _, err := o.Raw("SELECT * FROM label_info  where labelid = ?",deviceid ).QueryRows(&labelrows); err != nil{
		fmt.Println("err")
		return
	}
	var company = ""
	for _,labelrow := range labelrows{
		company = labelrow.Unit
		break
	}

	//将告警信息发布到redis
	//conn, _ := redis.Dial("tcp", "47.105.190.126:6379")
	conn, _ := redis.Dial("tcp", "192.168.1.109:6379")
	message := "alarm," + deviceid+","+company
	_,err1 := conn.Do("PUBLISH", "channel1", message)
	if err1 != nil {
		fmt.Println("pub err: ", err1)
		return
	}

	//_, err := o.Raw("update label_info set alarmflag = ? where labelid = ?", "1",deviceid).Exec()

    //添加告警记录
	alramdata := models.AlarmrecordInfo{Deviceid:deviceid, Devicetype:"安全帽标签",Company:company,Alarmtype:"紧急呼救", Alarmstamp:timeUnix,Alarmtime:timeStr}
	models.AddAlarm(&alramdata)

	type DATA struct {
		Deviceid string
	}
	type JSONS struct {
		//必须的大写开头
		Error_code int
		DATA DATA
	}

	if false  {
		data := &JSONS{1,DATA{deviceid}}
		c.Data["json"] = data
		c.ServeJSON()
	}else {
		data := &JSONS{0, DATA{deviceid}}
		c.Data["json"] = data
		c.ServeJSON()
	}
}

//设备收到手机的下行告警信息后取消
func (c *AlarmController) Canceldownwardwarning() {
	//fmt.Println("设备已收到手机到告警信息，请取消告警")
	FileLogs.Info("设备已收到手机到告警信息，请取消告警")
	deviceid := c.GetString("deviceid")
	o := orm.NewOrm()
	_, err := o.Raw("update label_info set alarmflag = ? where labelid = ?", "0",deviceid).Exec()


	//查询该设备所属公司
	var labelrows []models.LabelInfo
	if _, err := o.Raw("SELECT * FROM label_info  where labelid = ?",deviceid ).QueryRows(&labelrows); err != nil{
		FileLogs.Info( "数据库查询错误")
		return
	}
	var company = ""
	for _,labelrow := range labelrows{
		company = labelrow.Unit
		break
	}
	FileLogs.Info("获取公司",company)

     //将取消告警信息发布到redis
	conn, _ := redis.Dial("tcp", "192.168.1.109:6379")
	message := "cancel," + deviceid+"," + company
	_,err1 := conn.Do("PUBLISH", "channel1", message)
	if err1 != nil {
		FileLogs.Info("pub err: ", err1)
		return
	}

	type JSONS struct {
		//必须的大写开头
		Error_code int
	}

	if err != nil  {
		data := &JSONS{1,}
		c.Data["json"] = data
		c.ServeJSON()
	}else {
		data := &JSONS{0,}
		c.Data["json"] = data
		c.ServeJSON()
	}
}

